package com.horizon.common.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * Spring工具类
 *
 * @author wangfuwei
 * @version 2018-08-10
 */
@SuppressWarnings({"unused", "unchecked"})
@Component
public class SpringUtil implements ApplicationContextAware, EnvironmentAware {

    private static ApplicationContext applicationContext;

    private static Environment environment;

    /**
     * 根据类型获取Bean
     *
     * @param beanClass Class
     */
    public static <T> T getBean(Class beanClass) {
        return (T) applicationContext.getBean(beanClass);
    }

    /**
     * 根据名称获取Bean
     *
     * @param name 名称
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 获取配置文件信息
     *
     * @param key key
     */
    public static String getProperty(String key) {
        return environment.getProperty(key);
    }

    /**
     * 获取配置文件信息
     *
     * @param key key
     */
    public static <T> T getProperty(String key, Class<T> clazz) {
        return environment.getProperty(key, clazz);
    }

    /**
     * 获取配置文件信息
     *
     * @param key key
     */
    public static <T> T getProperty(String key, Class<T> clazz, T defaultValue) {
        return environment.getProperty(key, clazz, defaultValue);
    }

    /**
     * 发布事件
     *
     * @param event 事件
     */
    public static void publishEvent(ApplicationEvent event) {
        applicationContext.publishEvent(event);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringUtil.applicationContext = applicationContext;
    }

    @Override
    public void setEnvironment(Environment environment) {
        SpringUtil.environment = environment;
    }
}
